﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CoreCommon;
using CoreOracle;

namespace CoreOracle
{
    /// <summary>
    /// Форма соединения с базой данных Oracle
    /// </summary>
    public partial class FormConnect : Form
    {
        /// <summary>
        /// Вызов формы соединения с базой Oracle
        /// </summary>
        public static FormConnect Item
        {
            get 
            {
                return new FormConnect();
            }
        }

        /// <summary>
        /// Класс предоставляющей информацию о полученном соединении с базой
        /// </summary>
        public LogOnBase LogOnBase { get { return _logOnBase; } }

        #region Конструкторы

        private FormConnect()
        {
            InitializeComponent();
        }

        #endregion

        #region Обработка событий формы

        private void FormConnect_Load(object sender, EventArgs e)
        {
            textBoxServer.Text =  Log.ReadConfig()["Server"].ToString();
            userList = (SaveList)CoreSerialize.Deserialize(Path.GetDirectoryName(Application.ExecutablePath) + "\\users.dmp");

            if (userList != null)
            {
                List<string> sl = new List<string>();
                foreach (SaveItem si in userList.ListItems)
                {
                    cmsUsers.Items.Add(si.Name);
                    sl.Add(si.Name);
                }
                textBoxLogin.AutoCompleteCustomSource.AddRange(sl.ToArray());
            }
            else
            {
                userList = new SaveList();
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                // Проверка заполненности текстовых полей формы
                if (String.IsNullOrEmpty(textBoxLogin.Text.Trim()))
                    throw new CoreException(ErrType.Message, ErrorMsg.EmptyLogin);
                if (String.IsNullOrEmpty(textBoxServer.Text.Trim()))
                    throw new CoreException(ErrType.Message, ErrorMsg.EmptyServer);

                // Инициируем новое соединение с базой
                try
                {
                    _logOnBase = OraWork.LogOnBase();
                    if (DB.Item.IsActive)
                        _logOnBase.ReEnter(textBoxLogin.Text, textBoxPassword.Text, textBoxServer.Text);
                    else
                    {
                        DB.Item.Close();
                        _logOnBase.Enter(textBoxLogin.Text, textBoxPassword.Text, textBoxServer.Text);
                    }
                }
                catch (Exception err)
                {
                    throw new CoreException(ErrType.Message, ErrorMsg.ConnectError, err);
                }
                SaveItem si = new SaveItem(_logOnBase.Id, _logOnBase.LogOn, _logOnBase.LogOn);
                userList.Add(si);
                CoreSerialize.Serialize(Path.GetDirectoryName(Application.ExecutablePath) + "\\users.dmp", userList);
                this.DialogResult = DialogResult.OK;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void FormConnect_KeyDown(object sender, KeyEventArgs e)
        {
            bool legalControl = textBoxPassword.Focused || textBoxServer.Focused;

            if (e.KeyCode == Keys.Enter && legalControl)
                btnConnect_Click(null, null);
            else if (e.KeyCode == Keys.Enter && textBoxLogin.Focused)
                SetFocusOnTextBoxPassword();
        }
        private void cmsUser_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.textBoxLogin.Text = e.ClickedItem.Text;
            SetFocusOnTextBoxPassword();
        }
        private void btnOthers_Click(object sender, EventArgs e)
        {
            cmsUsers.Show(btnOthers, 0, btnOthers.Height + 2);
        }

        #endregion

        #region Private members

        private SaveList userList;
        private void SetFocusOnTextBoxPassword()
        {
            if (textBoxPassword.CanFocus)
                textBoxPassword.Focus();
        }
        private LogOnBase _logOnBase;

        #endregion

     }

}
